package command

import (
	"fmt"
	"strconv"
	"time"

	"github.com/pkg/errors"
	agentv1beta1 "gopkg.openfuyao.cn/bkeagent/api/v1beta1"
	bkenode "gopkg.openfuyao.cn/bkecommon/cluster/node"
)

type Hosts struct {
	BaseCommand

	Nodes bkenode.Nodes

	BkeConfigName string
}

func (e *Hosts) Validate() error {
	if e.Client == nil {
		return errors.New("client is nil")
	}
	if lenNodes := e.Nodes.Length(); lenNodes == 0 {
		return errors.New("env command except at least one node but got " + strconv.Itoa(lenNodes))
	}
	if e.BkeConfigName == "" {
		return errors.New("bkeConfigName is empty")
	}
	return e.BaseCommand.validate()
}

func (e *Hosts) New() error {
	if err := e.Validate(); err != nil {
		return err
	}
	// aright start create new env command
	bkeConfigStr := fmt.Sprintf("bkeConfig=%s:%s", e.NameSpace, e.BkeConfigName)

	commandName := fmt.Sprintf("%s-%d", K8sHostsCommandName, time.Now().Unix())
	commandSpec := GenerateDefaultCommandSpec()
	commandSpec.Commands = []agentv1beta1.ExecCommand{
		// init node hosts for node join or delete
		{
			ID: "init and check node env",
			Command: []string{
				"K8sEnvInit",
				"init=true",
				"check=true",
				"scope=hosts",
				bkeConfigStr,
			},
			Type:          agentv1beta1.CommandBuiltIn,
			BackoffDelay:  5,
			BackoffIgnore: false,
		},
	}

	commandSpec.NodeSelector = getNodeSelector(e.Nodes)

	return e.newCommand(commandName, BKEClusterLabel, commandSpec)
}
